package com.fzkj.nio.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 完成分散和聚集操作数据
 */
public class Test {

    public static void main(String[] args) {
        String sourcePath = "src/com/fzkj/nio/channel/data.txt";
        String targetPath = "E:/data1.txt";

        try{
            // 获取字节输入/输出流
            FileInputStream fis = new FileInputStream(sourcePath);
            FileOutputStream fos = new FileOutputStream(targetPath);
            // 获取输入/输出管道
            FileChannel isChannel = fis.getChannel();
            FileChannel osChannel = fos.getChannel();
            // 获取多个缓冲区
            ByteBuffer buf = ByteBuffer.allocate(5);
            ByteBuffer buf1 = ByteBuffer.allocate(1024);
            ByteBuffer[] buffers = {buf, buf1};

            // 从输入管道中读取数据分散放入各个缓冲区内
            isChannel.read(buffers);
            for (ByteBuffer buffer : buffers) {
                // 切换为读模式
                buffer.flip();
                System.out.println(new String(buffer.array(), 0, buffer.remaining()));
            }
            // 将数据聚集写入到输出管道中
            osChannel.write(buffers);
            isChannel.close();
            osChannel.close();
            System.out.println("文件复制成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
